package paylayer

import (
    "fmt"
	"strconv"
	"dhfshop/models/misc"
	"encoding/json"
	"dhfshop/models/isv"
	"dhfshop/utils/math"
	"dhfshop/utils/helper"
	"dhfshop/models/shopping"
	"thirdpaysdk/api/royalpay"
	"thirdpaysdk/api/yabandpay"
	"thirdpaysdk/api/dahlpay"
	"thirdpaysdk/api/superpay"
	"thirdpaysdk/api/usagms"
	"thirdpaysdk/api/wisecashier"
	"thirdpaysdk/api/megaezgo"
	"thirdpaysdk/api/chinaums"
	"thirdpaysdk/api/oceanpayment"
	"thirdpaysdk/api/qcurepay"
	"thirdpaysdk/api/hnapay"
	"thirdpaysdk/api/allinpay"
	"thirdpaysdk/api/gpslmall"
	"github.com/pkg/errors"
	"github.com/astaxie/beego"
)

func PreRefund(appId string, orderId int64, fee float32)(string,string,string,string,float32,error) {
	var refundFee float32 = 0.0
	payment, err := shopping.GetPaymentListByOrderId(orderId)
	if err != nil {
		return "","","","",refundFee,err
	}
	if fee > payment.PayFee {
		return "","","","",refundFee,errors.New("退款金额不能大于所支付金额")
	}
	if fee > 0 {
		refundFee = fee
	}else {
		refundFee = payment.PayFee
	}
	acPay, err := isv.GetParamsByAppIdOrSubAppId(appId)
	if err != nil {
		return "","","","",refundFee,err
	}
	mchId := acPay.MchId
	appKey := acPay.Appkey
	outerId := payment.OuterNo
	refundId, _:= misc.GetBillNo("PA")
	return mchId,appKey,outerId,refundId,refundFee,nil
}

func RoyalRefund(appId string,partnerId,storeId,memberId,orderId int64,fee float32)(string, error){
	mchId,appKey,_,refundId, refundFee, err := PreRefund(appId,orderId,fee)
	if err != nil {
	   beego.Debug("RoyalRefund:", err.Error())
	   return "", err
	}
	orderIdStr := strconv.FormatInt(orderId, 10)
	feeInt := int(math.MultiTotalPriceInt(refundFee, 100))
	refundRsp, err := royalpay.Refunds(mchId,orderIdStr,appKey,refundId,feeInt)
	if err != nil {
		return "", err
	}
	var srcData string
	var payFee float32 = math.DivTotalFee(float32(refundRsp.Amount), 100)  //微信返回的金额需要除以100
	if msgBody, err := json.Marshal(refundRsp); err == nil {
	   srcData = string(msgBody)
	}
	paymentId, err := shopping.AddPaymentByPayMsg(partnerId,storeId,memberId,orderId,3,
					"9",refundRsp.RefundId,refundRsp.Currency,"","",refundId,srcData,payFee,0,0,0)
	if err != nil {
		return "", err
	}
	return paymentId, nil
}

func YabandRefund(appId string,partnerId,storeId,memberId,orderId int64,fee float32)(string, error){
	var refundFee float32 = 0.0
	payment, err := shopping.GetPaymentListByOrderId(orderId)
	if err != nil {
		return "",err
	}
	if fee > payment.PayFee {
		return "",errors.New("退款金额不能大于所支付金额")
	}
	if fee > 0 {
		refundFee = fee
	}else {
		refundFee = payment.PayFee
	}
	acPay, err := isv.GetParamsByAppIdOrSubAppId(appId)
	if err != nil {
		return "",err
	}
	mchId := acPay.MchId
	secreCode := acPay.Appkey
	currency := acPay.MediaId
	user := acPay.SubMchId
	des := "YabandPay Refund Order"
	refundId, _:= misc.GetBillNo("PA")
	incompleteUrl := beego.AppConfig.String("WXPayNotify") + "/public/yabandpay/notify?merchant_id=%s"
	notifyUrl := fmt.Sprintf(incompleteUrl, mchId)
	refundFeeStr := strconv.FormatFloat(float64(refundFee), 'f', -1, 32)
	refundRsp, err := yabandpay.RefundPay(secreCode,payment.OuterNo,currency,des,user,notifyUrl,refundFeeStr)
	if err != nil {
		return "", err
	}
	var srcData string
	if msgBody, err := json.Marshal(refundRsp); err == nil {
	   srcData = string(msgBody)
	}	
	paymentId, err := shopping.AddPaymentByPayMsg(partnerId,storeId,memberId,orderId,3,
					"10",refundRsp.RefundData.TradeId,currency,"","",refundId,srcData,refundFee,0,0,0)
	if err != nil {
		return "", err
	}
	return paymentId, nil
}

func DahlRefund(appId string,partnerId,storeId,memberId,orderId int64,fee float32)(string, error){
	mchId,appKey,outerId,refundId,refundFee,err := PreRefund(appId,orderId,fee)
	if err != nil {
	   beego.Debug("DahlRefund:", err.Error())
	   return "", err
	}
	orderIdStr := strconv.FormatInt(orderId, 10)
	refundRsp, err := dahlpay.Refunds(mchId,appKey,orderIdStr,outerId,refundFee)
	if err != nil {
		return "", err
	}
	var srcData string
	if msgBody, err := json.Marshal(refundRsp); err == nil {
	   srcData = string(msgBody)
	}
	paymentId, err := shopping.AddPaymentByPayMsg(partnerId,storeId,memberId,orderId,3,
					"13",refundId,"","","",refundId,srcData,refundFee,0,0,0)
	if err != nil {
		return "", err
	}
	return paymentId, nil
}

func SuperPayRefund(appId string,partnerId,storeId,memberId,orderId int64,fee float32)(string, error){
	mchId,appKey,_,refundId,refundFee,err := PreRefund(appId,orderId,fee)
	if err != nil {
	   beego.Debug("DahlRefund:", err.Error())
	   return "", err
	}
	orderIdStr := strconv.FormatInt(orderId, 10)
	refundFeeStr :=  strconv.FormatFloat(float64(refundFee), 'f', -1, 32)
	callBackUrl := beego.AppConfig.String("WXPayNotify") + "/public/superpay/notify"
	refundRsp, err := superpay.Refund(mchId,appKey,callBackUrl,refundId,orderIdStr,refundFeeStr)
	if err != nil {
		return "", err
	}
	var srcData string
	if msgBody, err := json.Marshal(refundRsp); err == nil {
	   srcData = string(msgBody)
	}
	paymentId, err := shopping.AddPaymentByPayMsg(partnerId,storeId,memberId,orderId,3,
					"11",refundId,"","","",refundId,srcData,refundFee,0,0,0)
	if err != nil {
		return "", err
	}
	return paymentId, nil
}

func UsagmsRefund(appId string,partnerId,storeId,memberId,orderId int64,fee float32)(string, error){
	mchId,appKey,_,refundId, refundFee, err := PreRefund(appId,orderId,fee)
	if err != nil {
	   beego.Debug("UsagmsRefund:", err.Error())
	   return "", err
	}
	orderIdStr := strconv.FormatInt(orderId, 10)
	feeInt := int(math.MultiTotalPriceInt(refundFee, 100))
	refundRsp, err := usagms.Refunds(mchId,orderIdStr,appKey,refundId,feeInt)
	if err != nil {
		return "", err
	}
	var srcData string
	var payFee float32 = math.DivTotalFee(float32(refundRsp.Amount), 100)  //微信返回的金额需要除以100
	if msgBody, err := json.Marshal(refundRsp); err == nil {
	   srcData = string(msgBody)
	}
	paymentId, err := shopping.AddPaymentByPayMsg(partnerId,storeId,memberId,orderId,3,
					"12",refundRsp.RefundId,refundRsp.Currency,"","",refundId,srcData,payFee,0,0,0)
	if err != nil {
		return "", err
	}
	return paymentId, nil
}

func WiseCashierRefund(appId string,partnerId,storeId,memberId,orderId int64,fee float32)(string, error){
    var refundFee float32 = 0.0
	payment, err := shopping.GetPaymentListByOrderId(orderId)
	if err != nil {
		return "",err
	}
	if fee > payment.PayFee {
		return "",errors.New("退款金额不能大于所支付金额")
	}
	if fee > 0 {
		refundFee = fee
	}else {
		refundFee = payment.PayFee
	}
	acPay, err := isv.GetParamsByAppIdOrSubAppId(appId)
	if err != nil {
		return "",err
	}
	mchId := acPay.MchId
	privateKey := acPay.PemKey
	outerPayId := payment.OuterNo
	refundId, _:= misc.GetBillNo("PA")
	orderIdStr := strconv.FormatInt(orderId, 10)
	amount := strconv.FormatFloat(float64(refundFee), 'f', -1, 32)
	refundRsp, err := wisecashier.Refunds(mchId,outerPayId,orderIdStr,amount,privateKey)
	if err != nil {
		return "", err
	}
	var srcData string
	actRefundFee, _:= strconv.ParseInt(refundRsp.RefundData.RefundInfo.RefundAmount, 10, 64)
	var payFee float32 = math.DivTotalFee(float32(actRefundFee), 100)  //微信返回的金额需要除以100
	if msgBody, err := json.Marshal(refundRsp); err == nil {
	   srcData = string(msgBody)
	}
	paymentId, err := shopping.AddPaymentByPayMsg(partnerId,storeId,memberId,orderId,3,
					"14",refundRsp.RefundData.RefundInfo.No,"","","",refundId,srcData,payFee,0,0,0)
	if err != nil {
		return "", err
	}
	return paymentId, nil
}

func MegaezgoRefund(appId string,partnerId,storeId,memberId,orderId int64,fee float32)(string, error){
	var refundFee float32 = 0.0
	payment, err := shopping.GetPaymentListByOrderId(orderId)
	if err != nil {
		return "",err
	}
	if fee > payment.PayFee {
		return "",errors.New("退款金额不能大于所支付金额")
	}
	if fee > 0 {
		refundFee = fee
	}else {
		refundFee = payment.PayFee
	}
	acPay, err := isv.GetParamsByAppIdOrSubAppId(appId)
	if err != nil {
		return "",err
	}
	//
	//outerId := payment.OuterNo
	refundId, _:= misc.GetBillNo("PA")
	//
    apiStoreId := acPay.MchId
	apiStorePw := acPay.Appkey
	//barcodeSeq := acPay.SubMchId
	currency := acPay.MediaId
	//purposeType := acPay.SecondMchId
	privateKey := acPay.PemKey
	//
	orderIdStr := strconv.FormatInt(orderId, 10)
	feeInt := int(math.MultiTotalPriceInt(refundFee, 1))
    ipAddr, _:= helper.GetExternal()
	/*
    Refunds(apiStoreId,terminalIp,apiStorePw,refundNo,orderId,sysOrderNo,deviceInfo,
             currency string,orderAmount,RefundAmount int,privateKey []byte)
    */		 
	refundRsp, err := megaezgo.Refunds(apiStoreId,ipAddr,apiStorePw,refundId,orderIdStr,"","onlineCD",currency,feeInt,feeInt,[]byte(privateKey))
	if err != nil {
		return "", err
	}
	var srcData string
	var payFee float32 = math.DivTotalFee(float32(feeInt), 100)  //微信返回的金额需要除以100
	if msgBody, err := json.Marshal(refundRsp); err == nil {
	   srcData = string(msgBody)
	}
	paymentId, err := shopping.AddPaymentByPayMsg(partnerId,storeId,memberId,orderId,3,
					"15",refundId,currency,"","",refundId,srcData,payFee,0,0,0)
	if err != nil {
		return "", err
	}
	return paymentId, nil
}

func ChinaUmsRefund(appId string,partnerId,storeId,memberId,orderId int64,fee float32,subAccount string)(string, error){
	var refundFee float32 = 0.0
	payment, err := shopping.GetPaymentListByOrderId(orderId)
	if err != nil {
		return "",err
	}
	if fee > payment.PayFee {
		return "",errors.New("退款金额不能大于所支付金额")
	}
	if fee > 0 {
		refundFee = fee
	}else {
		refundFee = payment.PayFee
	}
	acPay, err := isv.GetParamsByAppIdOrSubAppId(appId)
	if err != nil {
		return "",err
	}
	mchId := acPay.MchId
	subMchId := acPay.SubMchId
	secreCode := acPay.Appkey
	msgSrc := acPay.PemCert
	orderIdStr := strconv.FormatInt(orderId, 10)
	feeInt := math.MultiTotalPriceInt(refundFee, 100)
	refundRsp, err := chinaums.RefundPay(mchId,subMchId,msgSrc,secreCode,orderIdStr,int(feeInt))
	if err != nil {
		return "", err
	}
	var srcData string
	var payFee float32 = math.DivTotalFee(float32(feeInt), 100)  //微信返回的金额需要除以100
	if msgBody, err := json.Marshal(refundRsp); err == nil {
	   srcData = string(msgBody)
	}
	paymentId, err := shopping.AddPaymentByPayMsg(partnerId,storeId,memberId,orderId,3,
					"16",refundRsp.RefundOrderId,"","","",refundRsp.RefundOrderId,srcData,payFee,0,0,0)
	if err != nil {
		return "", err
	}
	return paymentId, nil
}

func OceanPayRefund(appId string,partnerId,storeId,memberId,orderId int64,fee float32)(string, error){
	var refundFee float32 = 0.0
	payment, err := shopping.GetPaymentListByOrderId(orderId)
	if err != nil {
		return "",err
	}
	if fee > payment.PayFee {
		return "",errors.New("退款金额不能大于所支付金额")
	}
	if fee > 0 {
		refundFee = fee
	}else {
		refundFee = payment.PayFee
	}
	acPay, err := isv.GetParamsByAppIdOrSubAppId(appId)
	if err != nil {
		return "",err
	}
	account := acPay.MchId
	terminal := acPay.SubMchId
	appKey := acPay.Appkey
	//currency := acPay.MediaId
	orderIdStr := strconv.FormatInt(orderId, 10)
	amount := strconv.FormatFloat(float64(refundFee), 'f', -1, 32)
	//
	refundRsp, err := oceanpayment.Refunds(account,terminal,payment.OuterNo,orderIdStr,"1",amount,"客户不要了",appKey)
	if err != nil {
		return "", err
	}
	var srcData string
	if msgBody, err := json.Marshal(refundRsp); err == nil {
	   srcData = string(msgBody)
	}
	paymentId, err := shopping.AddPaymentByPayMsg(partnerId,storeId,memberId,orderId,3,
					"17",refundRsp.RefundId,"","","",refundRsp.RefundId,srcData,refundFee,0,0,0)
	if err != nil {
		return "", err
	}
	return paymentId, nil
}

func QcurePayRefund(appId string,partnerId,storeId,memberId,orderId int64,fee float32)(string, error){
	var refundFee float32 = 0.0
	payment, err := shopping.GetPaymentListByOrderId(orderId)
	if err != nil {
		return "",err
	}
	if fee > payment.PayFee {
		return "",errors.New("退款金额不能大于所支付金额")
	}
	if fee > 0 {
		refundFee = fee
	}else {
		refundFee = payment.PayFee
	}
	acPay, err := isv.GetParamsByAppIdOrSubAppId(appId)
	if err != nil {
		return "",err
	}
	orgCode := acPay.MchId
	merchCode := acPay.SubMchId
	appsecret := acPay.Appkey
	//currency := acPay.MediaId
	orderIdStr := strconv.FormatInt(orderId, 10)
	feeInt := int(math.MultiTotalPriceInt(refundFee, 100))
	refundId, _:= misc.GetBillNo("PA")
	//
	refundRsp, err := qcurepay.Refunds(orgCode,merchCode,appsecret,orderIdStr,refundId,"客户不要了",feeInt)
	if err != nil {
		return "", err
	}
	var srcData string
	if msgBody, err := json.Marshal(refundRsp); err == nil {
	   srcData = string(msgBody)
	}
	paymentId, err := shopping.AddPaymentByPayMsg(partnerId,storeId,memberId,orderId,3,
					"17",refundRsp.OrderNo,"","","",refundRsp.MerchOrderNo,srcData,refundFee,0,0,0)
	if err != nil {
		return "", err
	}
	return paymentId, nil
}

func HnapayRefund(appId string,partnerId,storeId,memberId,orderId int64,fee float32)(string, error){
	var refundFee float32 = 0.0
	payment, err := shopping.GetPaymentListByOrderId(orderId)
	if err != nil {
		return "",err
	}
	if fee > payment.PayFee {
		return "",errors.New("退款金额不能大于所支付金额")
	}
	if fee > 0 {
		refundFee = fee
	}else {
		refundFee = payment.PayFee
	}
	acPay, err := isv.GetParamsByAppIdOrSubAppId(appId)
	if err != nil {
		return "",err
	}
	refundId, _:= misc.GetBillNo("2019")
	//mchId := acPay.MchId
	merCode := acPay.SubMchId
	secreCode := acPay.Appkey
	currency := acPay.MediaId
	orderIdStr := strconv.FormatInt(orderId, 10)
	feeInt := math.MultiTotalPriceInt(refundFee, 100)
	notifyUrl := beego.AppConfig.String("WXPayNotify") + "/public/hnapay/notify"
	refundRsp, err := hnapay.Refunds(merCode,refundId,orderIdStr,int(feeInt),currency,notifyUrl,secreCode)
	if err != nil {
		return "", err
	}
	var srcData string
	var payFee float32 = math.DivTotalFee(float32(feeInt), 100)  //微信返回的金额需要除以100
	if msgBody, err := json.Marshal(refundRsp); err == nil {
	   srcData = string(msgBody)
	}
	paymentId, err := shopping.AddPaymentByPayMsg(partnerId,storeId,memberId,orderId,3,
					"16",refundRsp.Content.RefundOrderNo,"","","",refundRsp.Content.RefundOrderNo,srcData,payFee,0,0,0)
	if err != nil {
		return "", err
	}
	return paymentId, nil
}

func AllInPayRefund(appId string,partnerId,storeId,memberId,orderId int64,fee float32)(string, error){
	var refundFee float32 = 0.0
	payment, err := shopping.GetPaymentListByOrderId(orderId)
	if err != nil {
		return "",err
	}
	if fee > payment.PayFee {
		return "",errors.New("退款金额不能大于所支付金额")
	}
	if fee > 0 {
		refundFee = fee
	}else {
		refundFee = payment.PayFee
	}
	acPay, err := isv.GetParamsByAppIdOrSubAppId(appId)
	if err != nil {
		return "",err
	}
	custId := acPay.SubMchId
	secreCode := acPay.Appkey
	orderIdStr := strconv.FormatInt(orderId, 10)
	feeInt := int(math.MultiTotalPriceInt(refundFee, 100))
	feeIntStr := strconv.Itoa(feeInt)
    refundId, _:= misc.GetBillNo("PA")
	_, err = allinpay.Refunds(custId,appId,feeIntStr,refundId,orderIdStr,secreCode)
	if err != nil {
		return "", err
	}
	paymentId, err := shopping.AddPaymentByPayMsg(partnerId,storeId,memberId,orderId,3,
					"16",refundId,"","","",refundId,"",payment.PayFee,0,0,0)
	if err != nil {
		return "", err
	}
	return paymentId, nil
}

func GpslRefund(appId string,partnerId,storeId,memberId,orderId int64,fee float32)(string, error){
	//var refundFee float32 = 0.0
	payment, err := shopping.GetPaymentListByOrderId(orderId)
	if err != nil {
		return "",err
	}
	if fee > payment.PayFee {
		return "",errors.New("退款金额不能大于所支付金额")
	}
	//if fee > 0 {
	//	refundFee = fee
	//}else {
	//	refundFee = payment.PayFee
	//}
	acPay, err := isv.GetParamsByAppIdOrSubAppId(appId)
	if err != nil {
		return "",err
	}
	shopKey := acPay.SubMchId
	secreCode := acPay.Appkey
	//currency := acPay.MediaId
	orderIdStr := strconv.FormatInt(orderId, 10)
	err = gpslmall.Refund(shopKey,secreCode,orderIdStr)
	if err != nil {
		return "", err
	}
	refundOrderNo := ""
	paymentId, err := shopping.AddPaymentByPayMsg(partnerId,storeId,memberId,orderId,3,
					"16",refundOrderNo,"","","",refundOrderNo,"",payment.PayFee,0,0,0)
	if err != nil {
		return "", err
	}
	return paymentId, nil
}
